﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Web.UI.WebControls;

using System.Text.RegularExpressions;
using System.Data;
using System.Web.UI;

namespace 书籍与目录检索
{
    class BookSearch
    {
        mainForm myForm;

        //向前搜索数
        int iForward;
        string sConnStr;
        //最后一个找到的书籍序号
        int iLastBookIndex;
        int iBookFind;
        int iCurrentIndex;
        SqlConnection odcConnection;
        SqlCommand odCommand;
        delegate void SetTextCallback(string status,int amount, string message);//设置委托
        //初始化
        public BookSearch(mainForm _myForm , int _iForward, string _sConnStr)
        {
            myForm = _myForm;
            iForward = _iForward;
            sConnStr = _sConnStr;
            odcConnection = new SqlConnection(_sConnStr);
            iBookFind = 0;
            iCurrentIndex = 0;
        }

        public void Search()
        {
            //查找出所有目标小说站点
            SqlDataSource ds = new SqlDataSource();
            try
            {
                
                ds.ConnectionString = sConnStr;
                odcConnection.Open();
                odCommand = odcConnection.CreateCommand();
                setWorkStatus("检索站点信息", 0, "");
                BookSite[] sites = getBookSites();

                for (int i = 0; i < sites.Length; i++)
                {
                    //测试代码  i = sites.Length - 1;
                    iCurrentIndex = Convert.ToInt32(sites[i].BookLastIndex);
                    setWorkStatus("在" + sites[i].SiteName + "上检索", 0, "");
                    iLastBookIndex = iCurrentIndex;
                    while (iLastBookIndex + iForward > iCurrentIndex)
                    {
                        findBook(iCurrentIndex, sites[i]);

                        iCurrentIndex++;
                    }
                    ds.UpdateCommand = "update ls_Site set Site_BookLastIndex=" + iLastBookIndex + " where Site_ID=" + sites[i].SiteID;
                    ds.Update();
                }

            }
            catch (Exception ex)
            {
                setWorkStatus("", 0, "serch:" + ex.Data + ex.Message);

            }
            finally
            {
                ds.Dispose();
                odcConnection.Dispose();
            }
            
        }
        public void setWorkStatus(string status,int amount, string message)
        {
            //来设置工作状态，解决多线程下不能设置问题
            try
            {
                if (myForm.InvokeRequired)
                {
                    SetTextCallback d = new SetTextCallback(setWorkStatus);
                    myForm.Invoke(d, new object[] { status,amount, message });

                }
                else
                {
                    if (status != "")
                         myForm.lbBookStatus.Text= status;

                    if (message != "")
                        myForm.tbBookMessage.Text += message + "\r\n";

                    if (amount != 0)
                        myForm.tslBookCount.Text = (Convert.ToInt32(myForm.tslBookCount.Text) + amount).ToString();
                }
            }
            catch (Exception ex)
            {
                string info = ex.Message + ex.Data;
                // MessageBox.Show("设置工作状态" + ex.Message + ex.Message + ex.Data);
                setWorkStatus("", 0,"设置工作状态错误" + ex.Message + ex.Data + "\r\n");

            }

        }
        /// <summary>
        /// 查找书籍
        /// </summary>
        /// <param name="bookindex">书籍ID</param>
        /// <param name="booksite">书站信息</param>
        public void findBook(int bookindex, BookSite booksite)
        {
            string sBookName = "";
            string sBookWriter = "";
            string sCoverURL;
            string sBookRem;
            int iDir = bookindex / 1000;
            string sHtml = "";
            string sBookIndex = booksite.BookFormat.Replace("<#BOOK>", bookindex.ToString());
            sBookIndex = sBookIndex.Replace("<#DIR>", iDir.ToString());
            try
            {
                sHtml = GetData.getHtml(sBookIndex);

                if (sHtml != null && sHtml != "")
                {
                    Match match = Regex.Match(sHtml, booksite.BookName, RegexOptions.IgnoreCase | RegexOptions.Multiline);
                    if (match.Success)
                    {
                        sBookName = match.Groups[1].Value.Trim();

                        if (sBookName != "")
                        {

                            match = Regex.Match(sHtml, booksite.BookWriter, RegexOptions.IgnoreCase | RegexOptions.Multiline);
                            if (match.Success)
                            {
                                sBookWriter = match.Groups[1].Value.Trim();
                                match = Regex.Match(sHtml, booksite.BookCover, RegexOptions.IgnoreCase | RegexOptions.Multiline);
                                sCoverURL = match.Groups[1].Value;
                                if (sCoverURL.IndexOf("http://") != 0)
                                    sCoverURL = booksite.CoverFormat.Replace("<#COVER>", sCoverURL);

                                match = Regex.Match(sHtml, booksite.BookRem, RegexOptions.IgnoreCase | RegexOptions.Multiline);
                                sBookRem = match.Groups[1].Value;
                                sBookRem = GetData.clearHTML(sBookRem, "").Replace("'", "").Replace("-", "");
                                setWorkStatus(booksite.SiteName + ",当前序号：" + bookindex + ",成功访问" + iLastBookIndex + ",成功找到" + iBookFind + ",《" + sBookName + "》-" + sBookWriter, 0, "");

                                odCommand.CommandText = "insert into ls_Book(Book_Name,Book_Writer,Book_Cover,Book_Rem) select '" + sBookName + "','" + sBookWriter + "','" + sCoverURL + "',substring('" + sBookRem + "',1,500) where not exists (select * from ls_Book where Book_Name='" + sBookName + "')";

                                int i = odCommand.ExecuteNonQuery();
                                if (i == 1)
                                {
                                    iBookFind++;
                                    setWorkStatus("", 1, "《" + sBookName + "》" + sBookWriter + "-" + sCoverURL);
                                }
                                iLastBookIndex = bookindex;

                            }
                        }

                    }

                }
                setWorkStatus(booksite.SiteName + ",当前序号：" + bookindex + ",成功访问" + iLastBookIndex + ",成功找到" + iBookFind + ",《" + sBookName + "》-" + sBookWriter, 0, "");
            }
            catch (Exception ex)
            {
                setWorkStatus("", 0, "检索页面错误" + ex.Message + ex.Data + "\r\n");
            }
        }
        //获得所有的站点列表
        public BookSite[] getBookSites()
        {
            try
            {
                SqlDataSource ds = new SqlDataSource();

                ds.ConnectionString = sConnStr;
                ds.SelectCommand = "select Site_ID,Site_Name,Site_BookFormat,Site_BookName,Site_BookWriter,Site_BookCover,Site_CoverFormat,Site_BookRem,Site_BookLastIndex from ls_Site where Site_BookActive=1";
                DataView dv = (DataView)ds.Select(DataSourceSelectArguments.Empty);
                //建立读取总条数
                BookSite[] booksites = new BookSite[dv.Count];
                for (int i = 0; i < dv.Count; i++)
                {
                    booksites[i] = new BookSite();
                    booksites[i].BookName = dv[i]["Site_BookName"].ToString();
                    booksites[i].BookFormat = dv[i]["Site_BookFormat"].ToString();
                    booksites[i].BookWriter = dv[i]["Site_BookWriter"].ToString();
                    booksites[i].BookCover = dv[i]["Site_BookCover"].ToString();
                    booksites[i].CoverFormat = dv[i]["Site_CoverFormat"].ToString();
                    booksites[i].BookRem = dv[i]["Site_BookRem"].ToString();
                    booksites[i].BookLastIndex = dv[i]["Site_BookLastIndex"].ToString();
                    booksites[i].SiteID = dv[i]["Site_ID"].ToString();
                    booksites[i].SiteName = dv[i]["Site_Name"].ToString();
                }
                ds.Dispose();
                dv.Dispose();
                return booksites;
            }
            catch (Exception ex)
            {
                setWorkStatus("", 0, "获得BookSites出错"+ex.Message+ex.Data);
                throw (new Exception("获得BookSites出错" + ex.Message + ex.Data));
     
            }

        }
    }
}
